package com.epalmpay.service.sms.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.entity.GroupPayconfig;
import com.epalmpay.entity.GroupWxtemplate;
import com.epalmpay.mapper.GroupPayconfigMapper;
import com.epalmpay.mapper.GroupWxtemplateMapper;
import com.epalmpay.service.sms.ISMSService;
@Component("smsService") 
@Scope("singleton")
public class SMSServiceImpl implements ISMSService{

	
	 //产品名称:云通信短信API产品,开发者无需替换
   private static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
   private  static final String domain = "dysmsapi.aliyuncs.com";
   
   
//   private String  DEFAULT_ACCESSKEY;
//   
//   private String  DEFAULT_ACCESSKEY_SECRET;
   @Resource
	private  GroupPayconfigMapper groupPayconfigMapper;
   
   @Resource
  	private   GroupWxtemplateMapper groupWxtemplateMapper;
	/**
	 * 
	 * @param code  短信验证码
	 * @param templateType 模板类型
	 * @param strMobiles  群发 的接收手机号
	 * @param params 模板的其他参数值
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public  boolean sendRegionCode(Long groupId,String code,String templateType, ArrayList<String> strMobiles, Map<String, String> params)
			throws ApplicationException{
		
		 if(StringUtils.isBlank(templateType)||strMobiles==null||strMobiles.size()==0){
	        	throw new ApplicationException("主要参数不能为空");
	        }
		 //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        
        GroupPayconfig groupPayconfig= groupPayconfigMapper.selectGroupId(groupId);
        String accessKeyId="exjsVQTD9YD1zhou";
        String accessKeySecret="T6UafpL4wpqnzGndAg0b1aVWhDFeyf";
        String templateCode=templateType;
        String signName= "商博士智慧商圈";
        if(groupPayconfig!=null&&StringUtils.isNotBlank(groupPayconfig.getAliyunAccesskey())&&StringUtils.isNotBlank(groupPayconfig.getAliyunAccesskey())){
        	accessKeyId=groupPayconfig.getAliyunAccesskey();
        	accessKeySecret=groupPayconfig.getAliyunAccesskeySecret();
        	GroupWxtemplate groupWxtemplate=groupWxtemplateMapper.selectByTemplateTypeAndGroup(templateType, groupId);
        	templateCode=groupWxtemplate.getTemplateId();
        }else{
        	GroupWxtemplate groupWxtemplate=groupWxtemplateMapper.selectByTemplateTypeAndDefault(templateType);
        	if(groupWxtemplate!=null){
        		templateCode=groupWxtemplate.getTemplateId();
        	}
        }
        
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		} catch (ClientException e) {		
			e.printStackTrace();
			throw new ApplicationException("网络异常");
		}
        IAcsClient acsClient = new DefaultAcsClient(profile);

       
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        StringBuffer strMobile=new StringBuffer();
        for(String mobile :strMobiles){
        	if(strMobile.length()>0){
        		strMobile.append(",");
        	}
        	strMobile.append(mobile);
        }
        request.setPhoneNumbers(strMobile.toString());
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到     
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        StringBuffer buffer=new StringBuffer();
   	  Set<String>keyset=params.keySet();
   	 if(StringUtils.isNotBlank(code)){
   		 buffer.append("{\"code\":\"").append(code).append("\"");
   	 }else{
   		 buffer.append("{");
   	 }     
        if(params!=null&&params.size()>0){
        	//参数大于0       	  	
        	 for(String key :keyset){
        		 if(buffer.length()>2){
        			 buffer.append(",");
        		 }
        		 buffer.append("\"").append(key).append("\":\"").append(params.get(key)).append("\"");
        	 }
        }
        buffer.append("}");
        request.setTemplateParam(buffer.toString());
       
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHHmmss");
		String outOrderId= sdf.format(new Date())+code;
        request.setOutId(outOrderId);

        //hint 此处可能会抛出异常，注意catch
		try {
			SendSmsResponse	sendSmsResponse = acsClient.getAcsResponse(request);
			if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
				//请求成功
				return true;
			}else{
				 throw new ApplicationException(sendSmsResponse.getCode()+"#"+sendSmsResponse.getMessage());				
			}
		} catch (Exception e) {			
			e.printStackTrace();
			throw new ApplicationException("网络异常");
		}
			
		
	}
	@Override
	public boolean sendRegionCode(Long groupId, String code, String templateType, String strMobile, Map<String, String> params) throws ApplicationException {
		 if(StringUtils.isBlank(templateType)||StringUtils.isBlank(strMobile)){
	        	throw new ApplicationException("主要参数不能为空");
	        }
		 //可自助调整超时时间
     System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
     System.setProperty("sun.net.client.defaultReadTimeout", "10000");

     //初始化acsClient,暂不支持region化
     
   
     String accessKeyId="exjsVQTD9YD1zhou";
     String accessKeySecret="T6UafpL4wpqnzGndAg0b1aVWhDFeyf";
     String templateCode=templateType;
     String signName= "商博士智慧商圈";
     if(groupId!=null){
    	  GroupPayconfig groupPayconfig= groupPayconfigMapper.selectGroupId(groupId);
    	  if(groupPayconfig!=null&&StringUtils.isNotBlank(groupPayconfig.getAliyunAccesskey())&&StringUtils.isNotBlank(groupPayconfig.getAliyunAccesskey())){
    	     	accessKeyId=groupPayconfig.getAliyunAccesskey();
    	     	accessKeySecret=groupPayconfig.getAliyunAccesskeySecret();
    	     	int type = Integer.parseInt(params.get("type").toString());
    	     	GroupWxtemplate groupWxtemplate=groupWxtemplateMapper.selectByTemplateType(templateType, groupId, type);
    	     	templateCode=groupWxtemplate.getTemplateId();
    	     	signName = groupPayconfig.getSignName();
    	     }else{
    	     	GroupWxtemplate groupWxtemplate=groupWxtemplateMapper.selectByTemplateTypeAndDefault(templateType);
    	     	if(groupWxtemplate!=null){
    	     		templateCode=groupWxtemplate.getTemplateId();
    	     	}
    	     }
     }
    
     
     IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
     try {
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		} catch (ClientException e) {		
			e.printStackTrace();
			throw new ApplicationException("网络异常");
		}
     IAcsClient acsClient = new DefaultAcsClient(profile);

    
     //组装请求对象-具体描述见控制台-文档部分内容
     SendSmsRequest request = new SendSmsRequest();
     
     request.setPhoneNumbers(strMobile.toString());
     //必填:短信签名-可在短信控制台中找到
     request.setSignName(signName);
     //必填:短信模板-可在短信控制台中找到     
     request.setTemplateCode(templateCode);
     //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
     //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
     StringBuffer buffer=new StringBuffer();
	  Set<String>keyset=params.keySet();
	 if(StringUtils.isNotBlank(code)){
		 buffer.append("{\"code\":\"").append(code).append("\"");
	 }else{
		 buffer.append("{");
	 }     
     if(params!=null&&params.size()>0){
     	//参数大于0       	  	
     	 for(String key :keyset){
     		 if(buffer.length()>2){
     			 buffer.append(",");
     		 }
     		 buffer.append("\"").append(key).append("\":\"").append(params.get(key)).append("\"");
     	 }
     }
     buffer.append("}");
     request.setTemplateParam(buffer.toString());
    
     //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
     //request.setSmsUpExtendCode("90997");

     //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
     SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHHmmss");
		String outOrderId= sdf.format(new Date())+code;
     request.setOutId(outOrderId);

     //hint 此处可能会抛出异常，注意catch
		try {
			SendSmsResponse	sendSmsResponse = acsClient.getAcsResponse(request);
			if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
				//请求成功
				return true;
			}else{
				 throw new ApplicationException(sendSmsResponse.getCode()+"#"+sendSmsResponse.getMessage());				
			}
		} catch (Exception e) {			
			e.printStackTrace();
			throw new ApplicationException("网络异常");
		}
	}

	@Override
	public GroupPayconfig selectConfigByGroupid(Long groupid) {
		return groupPayconfigMapper.selectGroupId(groupid);
	}

	@Override
	public GroupWxtemplate selectTemplateConfigByGroupid(Long groupid, Integer type) {
		List<GroupWxtemplate> list = groupWxtemplateMapper.selectByGroupId(groupid, type);
		if(list.size()>0) {
			return list.get(0);
		} else {
			return null;
		}
	}
}
